<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-27 11:03:25
 * @LastEditTime: 2023-02-21 19:39:35
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 
 * @Motto: Write the code. Change the world.
-->
<template>
  <div
      class="new-bill route-page"
      :class="$store.getters.isMobile ? 'back-class' : ''"
  >
    <section v-if="!onlyBillInfo" class="header">
      <a-page-header class="hide-back" title="新建付款账单" @back="goBack"/>
    </section>
    <section class="content">
      <a-form layout="vertical">
        <a-row :gutter="12">
          <a-col :span="$store.getters.isMobile ? 24 : onlyBillInfo ? 24 : 12">
            <a-card title="账单信息">
              <a-row :gutter="12" :wrap="true">
                <a-col :span="$store.getters.isMobile ? 24 : 8" v-if="isRetreat">
                  <a-form-item label="关联合同" v-bind="validateInfos.contract_id">
                    <a-select
                      v-model:value="formData.contract_id"
                      placeholder="请选择"
                      :disabled="true"
                      :options="retreatContractOptions"
                    />
                  </a-form-item>
                </a-col>
                <a-col v-if="!onlyBillInfo" :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      label="关联合同"
                      v-bind="validateInfos.contract_id"
                  >
                    <a-select
                        v-model:value="formData.contract_id"
                        show-search
                        placeholder="输入租客名称搜索"
                        :default-active-first-option="false"
                        :filter-option="false"
                        :not-found-content="null"
                        :options="list.contractList"
                        @search="onContractSearch"
                        @select="handleContractSelect"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item label="收款方" v-bind="validateInfos.owner_id">
                    <a-select
                        :disabled="disabledOwner"
                        v-model:value="formData.owner_id"
                        show-search
                        placeholder="输入租客名称搜索"
                        :default-active-first-option="false"
                        :filter-option="false"
                        :not-found-content="null"
                        :options="list.ownerList"
                        @search="onOwenerSearch"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      label="费用类型"
                      v-bind="validateInfos.cost_type"
                  >
                    <a-cascader
                        v-model:value="formData.cost_type"
                        :options="list.costTypeList"
                        :load-data="getCostTypeSub"
                        placeholder="请选择"
                        @change="costTypeChange"
                        dropdownClassName="fee-type-cascader-custom"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item label="币种" v-bind="validateInfos.currency">
                    <a-select
                        v-model:value="formData.currency"
                        placeholder="请选择"
                        :options="list.currencyList"
                        disabled
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      v-bind="validateInfos.cost_period"
                  >
                    <template #label>
                      <span>计费周期</span>
                      <text-tip v-if="isRetreat" :tips="['计费周期选择范围不能超过租期时间']" />
                    </template>
                    <a-range-picker
                        v-model:value="formData.cost_period"
                        :disabled-date="disabledRangeDate"
                        :valueFormat="dateFormatStr"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      label="应付金额"
                      v-bind="validateInfos.receivable_payment"
                  >
                    <a-input-number
                        class="w-100p"
                        placeholder="请输入"
                        v-model:value="formData.receivable_payment"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      label="应付日期"
                      v-bind="validateInfos.receivable_payment_date"
                  >
                    <a-date-picker
                        class="w-100p"
                        v-model:value="formData.receivable_payment_date"
                        :valueFormat="dateFormatStr"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      v-bind="validateInfos.org_branch_id"
                  >
                    <template #label>
                      <span>所属公司</span>
                      <text-tip
                          :tips="[
                        '一旦选择公司，则代表该账单为该公司账单并且只能匹配该公司流水',
                      ]"
                      />
                    </template>
                    <a-select
                        v-model:value="formData.org_branch_id"
                        placeholder="请选择"
                        :options="list.companyList"
                        @change="changeOrgBranch"
                        :fieldNames="{
                      label: 'company',
                      value: 'id',
                    }"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="账单备注" v-bind="validateInfos.remark">
                    <a-textarea
                        placeholder="请输入"
                        :auto-size="{ minRows: 3 }"
                        v-model:value="formData.remark"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
          <a-col v-if="!onlyBillInfo" :span="$store.getters.isMobile ? 24 : 12" class="building">
            <a-card
                :bodyStyle="{
                height: '440px',
                overflow: 'hidden',
              }"
                title="请勾选房源"
            >
              <template #extra>
                <a-button
                    type="link"
                    @click="showSelectedHouse = !showSelectedHouse"
                    v-if="roomList.length"
                >
                  {{ showSelectedHouse ? "选择房源" : "查看已选" }}
                </a-button>
              </template>
              <ChooseHousingResources
                  v-show="!showSelectedHouse"
                  alertTip="不能跨项目选择房源"
                  :defaultChecked="{ roomList }"
                  limitType="village"
                  :areaEmptyDisabled="false"
                  :defaultCheckedChanged="defaultCheckedChanged"
                  @request="$utils.commonRequest"
                  @getResult="getRoomList"
                  @error="handleHousingCheckError"
                  :showRoomArea="false"
              />
              <CheckedHousingResources
                  v-show="showSelectedHouse"
                  :houseList="roomList"
              />
            </a-card>
          </a-col>
        </a-row>

        <section v-if="!onlyBillInfo" class="mt-10">
          <attachment-info
              :params="attachParams"
              typeFrom="bill"
              @getObjectId="getObjectId"
          />
        </section>

        <a-button
            v-if="!onlyBillInfo"
            type="primary"
            @click="addTurnover"
            size="large"
            ghost
            class="w-100p mt-20"
            v-show="!showTurnover"
        >
          <template #icon>
            <PlusOutlined/>
          </template>
          添加收支流水
        </a-button>

        <a-alert type="info" v-if="!processApprove && showTurnover" class="mt-20">
          <template #message>
            收支流水暂未开启审批，点击”
            <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
            <span v-else class="link" style="cursor: not-allowed;">配置</span>
            “可快速设置。
          </template>
        </a-alert>
        <a-card class="mt-20" title="收支流水" v-show="showTurnover">
          <template #extra>
            <a-button type="link" danger @click="removeTurnover">
              <template #icon>
                <DeleteOutlined/>
              </template>
            </a-button>
          </template>
          <a-row :gutter="12" :wrap="true">
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="借贷类型" v-bind="validateInfos.loan_type">
                <a-select
                    disabled
                    v-model:value="formData.loan_type"
                    placeholder="请选择"
                    :options="list.loanTypeList"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="发生额" v-bind="validateInfos.amount">
                <a-input-number
                    class="w-100p"
                    placeholder="请输入"
                    v-model:value="formData.amount"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="入账日期" v-bind="validateInfos.income_date">
                <a-date-picker
                    class="w-100p"
                    v-model:value="formData.income_date"
                    :valueFormat="dateFormatStr"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item
                  label="对方单位名称"
                  v-bind="validateInfos.company_name"
              >
                <a-input
                    class="w-100p"
                    placeholder="请输入"
                    v-model:value="formData.company_name"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item
                  label="流水账户"
                  v-bind="validateInfos.stream_account"
              >
                <a-select
                    v-model:value="formData.stream_account"
                    placeholder="请选择"
                    :options="accountOptions"
                    :fieldNames="{
                      label: 'name',
                      value: 'account_id',
                    }"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="匹配日期" v-bind="validateInfos.match_date">
                <a-date-picker
                    class="w-100p"
                    v-model:value="formData.match_date"
                    :valueFormat="dateFormatStr"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="联系人" v-bind="validateInfos.link_name">
                <a-input
                    class="w-100p"
                    placeholder="请输入"
                    v-model:value="formData.link_name"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="汇款方式" v-bind="validateInfos.remit_type">
                <a-select
                    v-model:value="formData.remit_type"
                    placeholder="请选择"
                    :options="list.remitTypeList"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item
                  label="对方账户"
                  v-bind="validateInfos.other_account"
              >
                <a-input
                    class="w-100p"
                    placeholder="请输入"
                    v-model:value="formData.other_account"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="凭证号" v-bind="validateInfos.voucher_no">
                <a-input
                    class="w-100p"
                    placeholder="请输入"
                    v-model:value="formData.voucher_no"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 8">
              <a-form-item label="收据编号" v-bind="validateInfos.receipt_no">
                <a-input
                    class="w-100p"
                    placeholder="请输入"
                    v-model:value="formData.receipt_no"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 12">
              <a-form-item label="流水摘要" v-bind="validateInfos.abstract">
                <a-textarea
                    placeholder="请输入"
                    :auto-size="{ minRows: 3 }"
                    v-model:value="formData.abstract"
                />
              </a-form-item>
            </a-col>
            <a-col :span="$store.getters.isMobile ? 24 : 12">
              <a-form-item
                  label="流水备注"
                  v-bind="validateInfos.stream_remark"
              >
                <a-textarea
                    placeholder="请输入"
                    :auto-size="{ minRows: 3 }"
                    v-model:value="formData.stream_remark"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </section>
    <section class="footer" :class="onlyBillInfo ? 'footer-in-drawer' : ''">
      <a-space v-if="!onlyBillInfo">
        <a-button type="primary" @click="submit(1)" :loading="loading">
          {{ processApprove && showTurnover ? '保存&发起审批' : '保存' }}
        </a-button>
        <a-button type="primary" @click="submit(2)" :loading="loading">
          {{ processApprove && showTurnover ? '保存&发起审批&新建下一个' : '保存&新建下一个' }}
        </a-button>
      </a-space>
      <a-space v-else>
        <a-button @click.stop="handleClose">取消</a-button>
        <a-button type="primary" :loading="loading" @click.stop="submit(1)"> {{ processApprove && showTurnover ? '保存&发起审批' : '保存' }}</a-button>
      </a-space>
    </section>
  </div>
</template>

<script>
import {computed, defineComponent, reactive, ref, toRaw, toRefs} from "vue";
import {useRouter} from "vue-router";
import {PlusOutlined, DeleteOutlined} from "@ant-design/icons-vue";
import {
  ChooseHousingResources,
  CheckedHousingResources,
  TextTip,
} from "bl-common-vue3";
import {Form, message} from "ant-design-vue";
import store from "../../../store";
import request from "../../../common/utils/request";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
import AttachmentInfo from "@/components/contract/AttachmentInfo/index.vue";
import _ from "lodash";
import moment from "moment";

export default defineComponent({
  name: "newPaymentBill",
  props: {
    // 租客信息 {id, name}
    ownerInfo: {
      type: Object,
      default: () => ({}),
    },
    onlyBillInfo: {
      type: Boolean,
      default: false, // 只有账单信息的drawer
    },
    /* 退租 retreat 特殊处理 */
    useType: {
      type: String,
      default: '',
    },
    useInfo: {
      type: Object,
      default: () => ({}),
    }
  },
  components: {
    ChooseHousingResources,
    CheckedHousingResources,
    PlusOutlined,
    DeleteOutlined,
    TextTip,
    AttachmentInfo,
  },
  setup(props, { emit }) {
    const $router = useRouter();
    const goBack = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetNeedRefreshPages",
          microInfo: {
            microId: `org_bill_refresh_page`,
            app: 'org',
            name: '账单列表',
            url: `/bill/billList`,
          }
        }, () => {
          const microId = window.microApp?.appName;
          window.microApp.forceDispatch({
            type: "SetMicroPagesDel",
            info: {
              microId: microId,
            },
          });
        })
      }
    };
    const disabledOwner = computed(() => !!props.ownerInfo.id);
    const isRetreat = computed(() => props.useType == 'retreat');

    /* 退租时选择计费周期范围不能超过租期时间 */
    const disabledRangeDate = (current) => {
      if (!isRetreat.value) return false;
      if (_.isEmpty(props.useInfo)) {
        return false;
      } else {
        return (
          current < moment(props?.useInfo?.lease_starttime).startOf("day") ||
          current > moment(props?.useInfo?.lease_endtime).endOf("days")
        )
      }
    };

    const state = reactive({
      showSelectedHouse: false,
      defaultCheckedChanged: 0,
      roomList: [],

      // 是否有审批
      processApprove: false,
      Approveis_admin: false,
      Approve_id: 0,
      object_id: '',
      attachParams: {
        type: 1,
      },
      retreatContractOptions: [],
      cost_type_txt: '',
    });

    const formData = ref({
      // 合同id
      contract_id: undefined,
      // 付款方
      owner_id: undefined,
      // 费用类型
      cost_type: undefined,
      // 币种
      currency: "CNY",
      // 计费周期
      cost_period: [],
      // 应收金额
      receivable_payment: "",
      // 应收日期
      receivable_payment_date: null,
      // 签署公司
      org_branch_id: undefined,
      // 账单备注
      remark: "",
      // 房源
    });
    const ruleRef = ref({
      owner_id: [{required: true, message: "必选"}],
      cost_type: [{required: true, message: "必选"}],
      cost_period: [{required: true, message: "必选"}],
      receivable_payment: [{required: true, message: "必填"}],
      receivable_payment_date: [{required: true, message: "必选"}],
    });

    const {resetFields, validate, validateInfos} = useForm(formData, ruleRef);

    const loading = ref(false);
    const submit = (type) => {
      if (!props.onlyBillInfo && !state.roomList.length) {
        message.warning("请选择房源！");
        return;
      }
      loading.value = true;
      validate()
          .then(() => {
            let params = JSON.parse(JSON.stringify(formData.value));
            if (props.onlyBillInfo) {
              let build_bind = {};
              if (props.useInfo?.build_bind) {
                build_bind = props.useInfo.build_bind;
              }
              params.lease_square = JSON.stringify(build_bind?.room);
              params.build_bind = JSON.stringify(build_bind);
            } else {
              const build_bind = {
                build: [],
                village: {},
                room: [],
              };
              const lease_square = [];
              build_bind.room = state.roomList.map((item) => {
                if (!build_bind.village.id) {
                  build_bind.village = {
                    id: item.extra.village_id,
                    name: item.extra.village_name,
                    short_name: item.extra.village_short_name,
                  };
                }
                const index = build_bind.build.findIndex(
                  (it) => it.id == item.extra.build_id
                );
                if (index == -1) {
                  build_bind.build.push({
                    id: item.extra.build_id,
                    build_number: item.extra.build_number,
                    build_name: item.extra.build_name,
                  });
                }
                let room = {
                  id: item.id,
                  layer_number: item.extra.layer_number,
                  layer_name: item.extra.layer_name,
                  room_number: item.room_number,
                  room_name: item.room_name,
                  lease_area: item.rental_area,
                  is_unreal: item?.is_unreal || 0,
                  lease_square: "squareMetre",
                  extra: item.extra || {},
                };
                lease_square.push(room);
                return room;
              });
              params.build_bind = JSON.stringify(build_bind);
              params.lease_square = JSON.stringify(lease_square);
            }
            params.bill_type = 2;
            params.object_id = state.object_id
            params.start_date = params.cost_period[0];
            params.end_date = params.cost_period[1];
            delete params.cost_period;
            params.hasPayStream = showTurnover.value ? 1 : 0;
            if (state.processApprove && showTurnover.value) {
              params.approval = state.processApprove
            }
            params.needMsg = true;
            if (params.cost_type && params.cost_type.length == 2) {
              params.cost_type = params.cost_type[1];
            } else {
              return;
            }
            if (isRetreat.value) {
              delete params.lease_square;
              params.is_append = true;
              params.cost_type_txt = state.cost_type_txt;
              params.actual_payment = '0.00';
              params.actual_retreat = params.receivable_payment;
              emit("handleSuccess", _.cloneDeep(params));
              return;
            }
            request.post("/org", "/org/createBill", params).then((res) => {
              message.success(res.msg || "保存成功!");
              if (props.onlyBillInfo) {
                emit('handleSuccess');
              } else {
                if (type == 1) {
                  goBack();
                }
                if (type == 2) {
                  resetFields();
                  removeTurnover();
                  state.roomList = [];
                  state.defaultCheckedChanged++;
                }
              }
            });
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const getRoomList = (detail) => {
      state.roomList = detail.roomList;
    };

    // 监听楼宇选择
    const handleBuildCheck = (e) => {
      // 选择了合同之后如果又选择其他楼宇，则取消关联合同
      const {checked} = e;
      if (checked && formData.value.contract_id) {
        formData.value.contract_id = undefined;
      }
    };

    const handleContractSelect = (value, option) => {
      if (option?.org_branch_id) {
        formData.value.org_branch_id = option.org_branch_id;
      } else {
        formData.value.org_branch_id = undefined;
      }
      if (
          option.build_bind &&
          option.build_bind.room &&
          option.build_bind.room.length
      ) {
        state.roomList = option.build_bind.room;
        state.defaultCheckedChanged++;
      }
    };

    const handleHousingCheckError = (info) => {
      if (info.type == "notFound") {
        formData.value.contract_id = undefined;
        state.roomList = [];
        message.error(
            "您没有权限访问合同绑定的楼宇，请先联系管理员添加楼宇权限。"
        );
      }
    };

    // 添加收支流水
    const showTurnover = ref(false);
    const turnoverForm = {
      // 借贷类型
      loan_type: "PAY",
      // 发生额
      amount: "",
      // 入账日期
      income_date: null,
      // 对方单位名称
      company_name: "",
      // 流水账户
      stream_account: undefined,
      // 	匹配日期
      match_date: "",
      // 	联系人
      link_name: "",
      // 汇款方式
      remit_type: undefined,
      // 对方账号
      other_account: "",
      // 	凭证号
      voucher_no: "",
      // 收据编号
      receipt_no: "",
      // 摘要
      abstract: "",
      // 备注
      stream_remark: "",
    };
    const turnoverRule = {
      loan_type: [{required: true, message: "必选"}],
      company_name: [{required: true, message: "必填"}],
      amount: [{required: true, message: "必填"}],
      income_date: [{required: true, message: "必选"}],
    };
    const addTurnover = () => {
      showTurnover.value = true;
      formData.value = {...formData.value, ...turnoverForm};
      ruleRef.value = {...ruleRef.value, ...turnoverRule};
    };

    const removeTurnover = () => {
      showTurnover.value = false;
      for (let key in turnoverForm) {
        delete formData.value[key];
      }
      for (let key in turnoverRule) {
        delete ruleRef.value[key];
      }
    };

    const onOwenerSearch = (value) => {
      getOwnerList(value, (result) => {
        list.ownerList = result;
      });
    };
    let timeout = null;
    let currentSearchValue = "";
    const getOwnerList = (value, callback) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      currentSearchValue = value;
      const getResult = () => {
        request
            .get("/org", "/owner/manage", {
              keywords: value,
              page: 1,
              pageSize: 20,
            })
            .then((res) => {
              if (currentSearchValue === value) {
                let result = [];
                if (res.list) {
                  result = res.list.map((item) => ({
                    value: item.id,
                    label: item.name,
                    build_bind: item.build_bind,
                  }));
                }
                callback(result);
              }
            });
      };
      timeout = setTimeout(getResult, 600);
    };
    const onContractSearch = (value) => {
      getContractList(value, (result) => {
        list.contractList = result;
      });
    };
    let timeout2 = null;
    let currentSearchValue2 = "";
    const getContractList = (value, callback) => {
      if (timeout2) {
        clearTimeout(timeout2);
        timeout2 = null;
      }
      currentSearchValue2 = value;
      const getResult = () => {
        request
            .get("/org", "/bill/relationContract", {
              keyword: value,
            })
            .then((res) => {
              if (currentSearchValue2 === value) {
                let result = [];
                if (res.list) {
                  result = res.list.map((item) => ({
                    value: item.id,
                    label: item.contract_number,
                    build_bind: item.build_bind,
                    org_branch_id: item.org_branch_id,
                  }));
                }
                callback(result);
              }
            });
      };
      timeout2 = setTimeout(getResult, 600);
    };

    const list = reactive({
      contractList: [],
      ownerList: [],
      costTypeList: [],
      currencyList: [],
      loanTypeList: [],
      remitTypeList: [],
      companyList: [],
    });

    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          list.costTypeList = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/bill/costList", {
            page: 1,
            limit: 9999,
            category_id: targetOption.value,
            status: 1,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.cost_type,
                isLeaf: true,
              }));
              list.costTypeList = [...list.costTypeList];
            }
          });
    };
    const getCompanyList = (id) => {
      request
          .get("/org", "/company/orgAndBranch", {})
          .then((res) => {
            list.companyList = res?.list || [];
            let defaultId = (res?.list || []).find((v) => v.id == id)?.id;
            let systemId = (res?.list || []).find((v) => v.is_system == 1)?.id;
            formData.value.org_branch_id = defaultId || systemId;
          });
    };

    const accountOptions = computed(() => {
      return list.companyList.find((v) => v.id == formData.value.org_branch_id)?.account_info || []
    });

    const changeOrgBranch = () => {
      if (formData.value?.stream_account || formData.value?.stream_account == 0) {
        formData.value.stream_account = undefined;
      }
    };

    const getDefaultCompany = () => {
      return new Promise((resolve) => {
        request.post("/org", "/company/getDefaultBranchId", {}).then((res) => {
          resolve(res?.org_branch_id);
        })
      });
    };

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'bill_stream_add'
      }).then((res) => {
        state.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id
      });
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    const getObjectId = (id) => {
      state.object_id = id;
    };

    const handleClose = () => {
      emit('handleClose')
    };

    const costTypeChange = (value, data) => {
      state.cost_type_txt = data[data.length - 1].label;
    };

    const init = () => {
      onOwenerSearch(props.ownerInfo.name || props.ownerInfo.owner_name || '');
      formData.value.owner_id = props?.ownerInfo?.id || undefined;
      getSetting()
      store.dispatch("BillInit").then((data) => {
        list.currencyList = data.currency;
        list.loanTypeList = data.loan_type;
        list.remitTypeList = data.remit_money;
        getCostTypeList();
        getDefaultCompany().then((id) => {
          getCompanyList(id);
        })
      });
      if (isRetreat.value) {
        // 退租时候 添加收款账单
        state.retreatContractOptions = props.useInfo?.id ? [
          {
            label: props?.useInfo?.contract_number,
            value: props.useInfo?.id,
          }
        ] : [];
        formData.value.contract_id = props.useInfo?.id || undefined;
      }
    };

    init();

    return {
      dateFormatStr,
      formData,
      validateInfos,
      list,
      showTurnover,
      loading,
      accountOptions,
      isRetreat,
      disabledOwner,
      ...toRefs(state),
      disabledRangeDate,
      handleClose,
      costTypeChange,
      getRoomList,
      handleBuildCheck,
      addTurnover,
      removeTurnover,
      goBack,
      onOwenerSearch,
      onContractSearch,
      submit,
      handleContractSelect,
      handleHousingCheckError,
      getCostTypeSub,
      changeOrgBranch,
      getSetting,
      goSetting,
      getObjectId,
    };
  },
});
</script>

<style lang="less" scoped>
.new-bill {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    height: 50px;
    background: #fff;

    &:deep(.ant-page-header) {
      padding: 10px 20px;
    }
  }

  .content {
    flex: 1;
    padding: 10px;
    margin: 10px;
    max-height: calc(~"100%- 160px");
    overflow-y: auto;

    .building {
      height: 500px;
    }
  }

  .footer {
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 20px;
    box-sizing: border-box;
    background: #f7f7f7;
  }

  .footer-in-drawer {
    border-top: 1px solid #e9e9e9;
    background-color: #fff;
  }

  &.back-class {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }
}
.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}
</style>
